<script lang="ts" setup>
import {onMounted, reactive, ref} from 'vue'
import {useRouter} from 'vue-router'
import {Modal} from 'ant-design-vue'
import {error, handleError, success} from '@/utils/message'
import {PICTURE} from '@/constants/messages'
import {DownloadOutlined, EyeOutlined, PictureOutlined, UploadOutlined} from '@ant-design/icons-vue'
import MainLayout from '@/components/layout/MainLayout.vue'
import ProgressiveImage from '@/components/common/ProgressiveImage.vue'
import {pictureApi, spaceApi} from '@/api'
import {useAuthStore} from '@/stores/modules/auth'
import type {PictureVO} from '@/types/vo/picture'
import type {SpaceVO} from '@/types/vo/space'
import {PICTURE_CATEGORIES} from '@/constants/picture'

const router = useRouter()
const authStore = useAuthStore()

const loading = ref(false)
const pictureList = ref<PictureVO[]>([])
const mySpaces = ref<SpaceVO[]>([])
const pagination = reactive({
  current: 1,
  size: 12,
  total: 0
})

const filterParams = reactive({
  category: '',
  spaceId: undefined as undefined | null | number  // undefined=全部空间，null=公共空间，数字=具体空间
})

// 加载我的空间列表
const loadMySpaces = async () => {
  try {
    const result = await spaceApi.getMySpaces()
    mySpaces.value = [...result.owner, ...result.joined]
  } catch (error: any) {
    // 静默失败，不影响主流程
  }
}

// 加载图片列表
const loadPictures = async () => {
  if (!authStore.user) {
    error('请先登录')
    router.push('/login')
    return
  }

  loading.value = true
  try {
    const params: any = {
      current: pagination.current,
      size: pagination.size,
      userId: authStore.user.id
    }

    if (filterParams.category) {
      params.category = filterParams.category
    }
    // 处理空间筛选：undefined=全部，null=公共空间，数字=具体空间
    if (filterParams.spaceId !== undefined) {
      params.spaceId = filterParams.spaceId
    }

    const result = await pictureApi.list(params)
    pictureList.value = result.records
    pagination.total = result.total
  } catch (error: any) {
    handleError(error, PICTURE.LOAD_FAILED)
  } finally {
    loading.value = false
  }
}

// 筛选
const handleFilter = () => {
  pagination.current = 1
  loadPictures()
}

// 分页变化
const handlePageChange = () => {
  loadPictures()
  window.scrollTo({top: 0, behavior: 'smooth'})
}

// 删除图片
const handleDelete = (picture: PictureVO) => {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除图片"${picture.pictureName}"吗？此操作不可恢复。`,
    okText: '确定',
    okType: 'danger',
    cancelText: '取消',
    onOk: async () => {
      try {
        await pictureApi.delete(picture.id!)
        success(PICTURE.DELETE_SUCCESS)
        loadPictures()
      } catch (error: any) {
        handleError(error, PICTURE.DELETE_FAILED)
      }
    }
  })
}

onMounted(() => {
  loadMySpaces()
  loadPictures()
})
</script>

<template>
  <main-layout>
    <div class="my-pictures-container">
      <a-card>
        <template #title>
          <a-space>
            <PictureOutlined/>
            <span>我的图片</span>
          </a-space>
        </template>
        <template #extra>
          <a-button type="primary" @click="$router.push('/picture/upload')">
            <template #icon>
              <UploadOutlined/>
            </template>
            上传图片
          </a-button>
        </template>

        <!-- 筛选器 -->
        <div class="filters">
          <a-space wrap>
            <a-select
                v-model:value="filterParams.category"
                allowClear
                placeholder="分类筛选"
                style="width: 150px"
                @change="handleFilter"
            >
              <a-select-option value="">全部分类</a-select-option>
              <a-select-option
                  v-for="cat in PICTURE_CATEGORIES"
                  :key="cat.value"
                  :value="cat.value"
              >
                {{ cat.label }}
              </a-select-option>
            </a-select>

            <a-select
                v-model:value="filterParams.spaceId"
                allowClear
                placeholder="空间筛选"
                style="width: 200px"
                @change="handleFilter"
            >
              <a-select-option :value="undefined">全部空间</a-select-option>
              <a-select-option :value="null">公共空间</a-select-option>
              <a-select-option
                  v-for="space in mySpaces"
                  :key="space.id"
                  :value="space.id"
              >
                {{ space.spaceName }}
              </a-select-option>
            </a-select>
          </a-space>
        </div>

        <!-- 图片列表 -->
        <a-spin :spinning="loading" style="margin-top: 24px">
          <div v-if="pictureList.length > 0" class="pictures-grid">
            <div
                v-for="picture in pictureList"
                :key="picture.id"
                class="picture-item"
            >
              <div class="picture-cover" @click="$router.push(`/picture/${picture.id}`)">
                <progressive-image
                    :alt="picture.pictureName"
                    :lazy="true"
                    :src="picture.thumbnailUrl || picture.fileUrl"
                />
                <div class="picture-mask">
                  <a-space>
                    <span><EyeOutlined/> {{ picture.viewCount || 0 }}</span>
                    <span><DownloadOutlined/> {{ picture.downloadCount || 0 }}</span>
                  </a-space>
                </div>
              </div>
              <div class="picture-info">
                <div class="picture-title">{{ picture.pictureName }}</div>
                <div class="picture-actions">
                  <a-space>
                    <a-button size="small" type="link" @click="$router.push(`/picture/${picture.id}`)">
                      查看
                    </a-button>
                    <a-button danger size="small" type="link" @click="handleDelete(picture)">
                      删除
                    </a-button>
                  </a-space>
                </div>
              </div>
            </div>
          </div>

          <a-empty v-else description="还没有上传图片" style="margin: 60px 0">
            <template #footer>
              <a-button type="primary" @click="$router.push('/picture/upload')">
                立即上传
              </a-button>
            </template>
          </a-empty>

          <!-- 分页 -->
          <div v-if="pagination.total > 0" class="pagination">
            <a-pagination
                v-model:current="pagination.current"
                v-model:page-size="pagination.size"
                :show-total="(total: number) => `共 ${total} 张图片`"
                :total="pagination.total"
                show-size-changer
                @change="handlePageChange"
            />
          </div>
        </a-spin>
      </a-card>
    </div>
  </main-layout>
</template>

<style lang="scss" scoped>
@use '@/assets/styles/variables.scss' as *;
@use '@/assets/styles/components.scss' as *;

.my-pictures-container {
  @include container;
  padding: $spacing-xl $spacing-lg;

  @include responsive($breakpoint-md) {
    padding: $spacing-lg $spacing-md;
  }
}

.filters {
  margin-bottom: $spacing-xl;

  :deep(.ant-card) {
    border-radius: $radius-lg;
    box-shadow: $shadow-sm;
  }

  :deep(.ant-select) {
    .ant-select-selector {
      border-radius: $radius-md;
    }
  }
}

.pictures-grid {
  @include pictures-grid;
}

.picture-item {
  @include picture-card;

  .picture-cover {
    :deep(.progressive-image) {
      width: 100%;
      border-radius: 0;
    }
  }

  .picture-info {
    .picture-actions {
      display: flex;
      justify-content: flex-end;
      gap: $spacing-xs;

      :deep(.ant-btn:hover) {
        transform: translateY(-1px);
      }
    }
  }
}

.pagination {
  @include pagination;
}
</style>